﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Yala.Core.Authentication;
using DotNetOpenAuth.OpenId.RelyingParty;
using System.Dynamic;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

namespace Yala.Client.Web.MVC.Infrastructure.Membership {

    public class OpenIdMembership : IMembership {
        public dynamic ValidateUser(string serviceUrl) {
            dynamic result = new ExpandoObject();
            // FIXME: Hook into Yala.Core DotNetOpenAuthManager to do the authentication
            var openId = new OpenIdRelyingParty();
            var response = openId.GetResponse();
           
            if (response == null) {
                result.Authenticated = response != null;

                // Create a request and redirect the user
                using (var openid = new OpenIdRelyingParty()) {
                    var request = openid.CreateRequest(serviceUrl);
                    var fetch = new FetchRequest();
                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                    request.AddExtension(fetch);
                    request.RedirectToProvider();
                }
            } else {

                // We got a response - check it's valid and that it's me
                if (response.Status == AuthenticationStatus.Authenticated) {
                    result.Authenticated = true;

                    //Set the openId
                    result.ClaimId = response.ClaimedIdentifier.ToString();

                    // Check and get the email
                    var friendlyId = response.FriendlyIdentifierForDisplay;
                    var fetch = response.GetExtension<FetchResponse>();
                    if (fetch != null) {
                        result.Email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                    }
                } else {
                    result.Authenticated = false;
                }
            }
            return result;
        }

        public dynamic ValidateUser(string username, string password) {
            throw new NotImplementedException();
        }
    }
}